﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

/// <summary>
/// 加到新的场景对象上,每个场景都重新绑定一次
/// </summary>
public class ScenePlayerLogic : MonoBehaviour
{
    //private static ScenePlayerLogic self;

    private List<GameObject> objList = new List<GameObject>();

    private Boolean _playerVisible = true;

    private GameObject[] npcList;

    public ScenePlayerLogic() { }

    /// <summary>
    /// 初始化场景物体的本地配置(改为动态加载，放在每个初始化gameobj后面)
    /// </summary>
    //void Awake()
    //{
    //    npcList = GameObject.FindGameObjectsWithTag("SceneObject");
    //    for (int i = 0; i < npcList.Length; i++)
    //    {
    //        objList.Add(npcList[i]);
    //        string name = npcList[i].name;//从101101中获取类型以初始化对应的结构表//
    //        //string[] strArr = name.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);//存在数位的转换(Npc001_4_1)//

    //        string[] ConfigInfo = SqliteReader.getInstance().getIniVal("scene", "NpcName", name, new string[] { "ID", "Type", "Index" });//scene通过服务器消息取得//
    //        int typeId = int.Parse(ConfigInfo[0]);
    //        int type = int.Parse(ConfigInfo[1]);
    //        int index = int.Parse(ConfigInfo[2]);

    //        Point objID = new Point();
    //        objID.SetObjectID(1, typeId, (UInt32)type, (UInt32)index);//123421:2//
    //        npcList[i].name = objID.ToString();//转换为objID名//

    //        SceneObject sceneObj = new SceneObject(objID, 0, 0);

    //        string[] ConfigBase = SqliteReader.getInstance().getIniVal("TeplatesInfo", "OType", type.ToString(), new string[] { "Struct", "Config", "Key" });

    //        InitXML.getInstance().AnalyzeXml(ConfigBase[0], ConfigBase[1], ConfigInfo[2], typeId.ToString(), sceneObj);//初始化本地配置(结构表，数据库配置，配置文件的key值)//

    //    }
    //}

    void Update()
    {
        GameObject[] arrObj = objList.ToArray();
        arrObj = BubbleSort(arrObj);

        float indexStartVal = 0;

        foreach (GameObject obj in arrObj)
        {
            Vector3 pos = Camera.mainCamera.WorldToScreenPoint(obj.transform.position);
            if (pos.x < 0 || pos.x > Screen.width)
            {
                obj.SetActive(false);
            }
            else
            {
                obj.SetActive(true);
            }
        }

        foreach (GameObject obj in arrObj)
        {
            if (obj.activeSelf)
            {
                Vector3 pos = obj.transform.localPosition;
                obj.transform.localPosition = new Vector3(pos.x, pos.y, indexStartVal);
                indexStartVal += 0.001f;
            }
        }

        WalkLogic.getInstance().encounterMonster(arrObj);
    }

    public GameObject[] BubbleSort(GameObject[] list)
    {
        int i;
        GameObject temp;
        for (int j = 0; j < list.Length; j++)
        {
            for (i = list.Length - 1; i > j; i--)
            {
                if (list[j].transform.localPosition.y > list[i].transform.localPosition.y)
                {
                    temp = list[j];
                    list[j] = list[i];
                    list[i] = temp;
                }
            }
        }
        return list;
    }

    /// <summary>
    /// 场景对象是否可见
    /// </summary>
    public Boolean playerVisible
    {
        get { return _playerVisible; }
    }

    /// <summary>
    /// 每次清空场景之后需要增加主角对象
    /// </summary>
    public void removeAllObjs()
    {
        objList.Clear();
    }

    public int playerMax
    {
        get { return objList.Count; }
    }

    //public static ScenePlayerLogic getInstance()
    //{
    //    if (self == null)
    //    {
    //        self = new ScenePlayerLogic();
    //    }
    //    return self;
    //}

    public GameObject[] sceneObjArr
    {
        get
        {
            GameObject[] gb = objList.ToArray();
            return gb;
        }
    }

    public void addNpc(GameObject gameObj)
    {
        objList.Add(gameObj);
        ModelLocator.getInstance().dispacthEvent(ClientToClientFlag.SERVER_ADD_SCENEOBJ,new object[]{ gameObj });
    }
    /// <summary>
    /// 场景增加对象
    /// </summary>
    /// <param name="obj">对象ID，作为唯一对象名</param>
    public void addNpc(Point objId)
    {
        if (getScenePlayerByID(objId) == null)
        {
            //实例化场景显示对象GameObject，并绑定对应脚本
            //            
            //            //gameObj.AddComponent();//需继承MonoBehaviour
            //            //可根据数据层，初始化坐标
            //            gameObj.name = objId.ToString();
            //            gameObj.SetActive(_playerVisible);
            //            objList.Add(gameObj);

            Transform parentTrans = GameObject.Find("Panel(NPC)").transform;

            string filePath = ResPath.PREFABPATH + "Player";
            GameObject player = (GameObject)MonoBehaviour.Instantiate(Resources.Load(filePath));

            SceneObject scenePlayer = (SceneObject)ModelLocator.getInstance().scene.GetProperties(objId.ToString());
            string playerName = (string)scenePlayer.GetProperties("PlayerName");
            string profession = (string)scenePlayer.GetProperties("Profession");
            string modelPath = (string)scenePlayer.GetProperties("ModelPath");
            string PosX = (string)scenePlayer.GetProperties("PosX");
            string PosY = (string)scenePlayer.GetProperties("PosY");

            player.transform.parent = parentTrans.transform;
            player.transform.localPosition = new Vector3(int.Parse(PosX), int.Parse(PosY), 0);
            player.transform.localScale = Vector3.one;
            player.name = objId.ToString();
            player.tag = "SceneObject";

            UILabel nameLabel = player.GetComponentInChildren<UILabel>();
            nameLabel.text = playerName;

            ClipAnimation clipAni = player.GetComponentInChildren<ClipAnimation>();
            clipAni.filePath = modelPath;

            PlayerAction pa = player.GetComponent<PlayerAction>();
            //Speed
            pa.speed = 0.9f;


            player.SetActive(_playerVisible);
            objList.Add(player);

            ModelLocator.getInstance().dispacthEvent(ClientToClientFlag.SERVER_ADD_SCENEOBJ, new object[] { player });
        }
    }
    /// <summary>
    /// 初始化显示到场景,对应的组建已经全部可视化的绑定到对象上
    /// </summary>
    /// <param name="parent">父容器</param>
    /// <param name="_path">模型地址</param>
    /// <returns></returns>
    private static GameObject InitToParent(GameObject parent, string _path)
    {
        GameObject obj = (GameObject)Instantiate(Resources.Load(_path));
        if (parent != null)
        {
            obj.transform.parent = parent.transform;
            obj.transform.localScale = new Vector3(1, 1, 1);
            obj.transform.localPosition = new Vector3(0, 0, 0);
        }
        return obj;
    }

    /// <summary>
    /// 场景移除对象
    /// </summary>
    public void removeNpc(Point objID)
    {
        GameObject obj = getScenePlayerByID(objID);
        if (objList.IndexOf(obj) != -1)
        {
            //销毁GameObject
            objList.Remove(obj);
            Destroy(obj);
            obj = null;
            Resources.UnloadUnusedAssets();
        }
    }

    /// <summary>
    /// 更新场景对象属性信息
    /// </summary>
    /// <param name="npcObj"></param>
    /// <param name="propertyName"></param>
    public void updataSceneObjByProperty(SceneObject npcObj, string propertyName)
    {
        GameObject obj = getScenePlayerByID(npcObj.ObjID);
        //SceneObject npcModel = obj.GetComponent<SceneObject>();//按照不同的属性变动取对应所影响的组建
        //if (npcModel != null)
        //{
        //    switch (propertyName)
        //    {
        //        case "CantVisible":
        //            {
        //                obj.SetActive((int)npcObj.GetProperties("CantVisible") != 1);
        //                break;
        //            }
        //        case "HP":
        //        case "MaxHP":
        //            {
        //                break;
        //            }
        //    }
        //}
    }

    public GameObject getScenePlayerByID(string objID)
    {
        Point point = new Point();
        point.z = ulong.Parse(objID);
        return getScenePlayerByID(point);
    }
    public GameObject getScenePlayerByID(Point objID)
    {
        foreach (GameObject obj in objList)
        {
            if (obj.name == objID.ToString())
            {
                return obj;
            }
        }
        return null;
    }

    /// <summary>
    /// 控制所有场景玩家的显示隐藏
    /// </summary>
    public void changePlayerVisible(Boolean val)
    {
        if (val != _playerVisible)
        {
            _playerVisible = val;
            foreach (GameObject obj in objList)
            {
                string name = obj.name;
                SceneObject sceneObj = ModelLocator.getInstance().scene.GetProperties(name) as SceneObject;
                if ((int)sceneObj.GetProperties("type") == ObjType.Player)//改变场景上player的显示隐藏,其他场景物体不变//
                {
                    obj.SetActive(val);
                }
            }
        }
    }


}